package com.iwhalecloud.bss.kite.cucc.web.service.scene;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import com.iwhalecloud.bss.kite.cucc.client.api.inf.IInfUnifyService;
import com.iwhalecloud.bss.kite.cucc.client.vo.order.PropertyValueVO;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.api.scene.query.IQuerySceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.inst.InstAttrDTO;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.cache.impl.KiteContextCache;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.log.KiteLogEnum;
import com.iwhalecloud.bss.kite.common.log.KiteLogger;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteSpringUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.IIndustryService;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.ILocalQueryScenePersonInfoService;
import com.iwhalecloud.bss.kite.cucc.client.api.inf.IInfServiceBus;
import com.iwhalecloud.bss.kite.cucc.client.api.order.ICommonSevice;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.KiteIndustryConfig;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAgentDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAttachmentDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAttrDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosDeveloperDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosLinkmanDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosOperatorDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosOrderDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosUserDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.webService.QryIOTOppoDockingSalesRsp;
import com.iwhalecloud.bss.kite.cucc.client.enumerate.UserDetailTagName;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.AttachmentVO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.CuccChannelCache;
import com.iwhalecloud.bss.kite.cucc.service.attr.LocalAttrHelper;
import com.iwhalecloud.bss.kite.cucc.service.order.RegistrationService;
import com.iwhalecloud.bss.kite.cucc.service.util.ChangeTypeUtils;
import com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr.IPersonAttrDealService;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.entity.AttrValue;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttrValue;
import com.iwhalecloud.bss.kite.service.util.CopyToDtoUtil;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.ICommonAttrDealService;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.ICommonAttrHandler;
import com.iwhalecloud.bss.kite.web.service.accept.util.HandlerFactoryUtils;
import com.ztesoft.bss.common.bo.LoginInfo;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.bss.order.base.consts.KeyValues;

/**
 * Created by huanghaosheng on 2021/3/9 17:29
 */
@Service
public class CommonSevice implements ICommonSevice {

    @Autowired
    private IPersonAttrDealService personAttrDealService;

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    IOperateSceneInstService operateSceneInstService;

    @Autowired
    private IQuerySceneCommonService querySceneCommonService;

    @Autowired
    private IInfServiceBus infServiceBus;

    @Autowired
    private ICommonAttrDealService commonAttrDealService;

    @Autowired
    private ILocalQueryScenePersonInfoService queryScenePersonService;

    @Autowired
    private RegistrationService registrationService;

    @Autowired
    private IInfUnifyService iInfUnifyService;

    @Override
    @KiteLogger(isWrite = true, type = KiteLogEnum.SERVICE)
    public void initCommonAttrValues(String sceneInstId, String serviceOfferId, String custId, KitePosDTO kitePosDTO, LoginInfo loginInfo) {
        //先初始化公共属性，这里直接初始化公共属性
        this.personAttrDealService.initAttr(sceneInstId, custId, Boolean.FALSE);
        List<KitePosUserDTO> users = kitePosDTO.getUsers();
        // 获取用户原始数据。主要用于实例还原
        Map<String, Object> userDetail = queryCommonInfoOriginValue(loginInfo, users, sceneInstId, serviceOfferId);

        if (!KiteListUtils.isEmpty(users)) {
            Map<String, Object> userInfo = (Map<String, Object>) userDetail.get("USER_INFO");
            /*setCommonAttrValue(sceneInstId, "SERVICE_STATE_CODE", KiteMapUtils.getStrValue(userInfo, "SERVICE_STATE_CODE"), KiteMapUtils.getStrValue(userInfo, "SERVICE_STATE_CODE"),
                KiteMapUtils.getStrValue(userInfo, "SERVICE_STATE_CODE"));*/
            List<KitePosUserDTO> oldUserInfos = this.querySceneInstService.getExtParameterValue(sceneInstId, "userInfos");
            if (!KiteListUtils.isEmpty(oldUserInfos)) {
                List<KitePosAttrDTO> attrs = Optional.ofNullable(oldUserInfos.get(0).getAttrs()).orElse(Lists.newArrayList());
                attrs.add(this.newUserAttr("serviceStateCode", KiteMapUtils.getStrValue(userInfo, "SERVICE_STATE_CODE")));
                oldUserInfos.get(0).setAttrs(attrs);
                this.operateSceneInstService.putExtParameter(sceneInstId, "userInfos", oldUserInfos);
            }

            // 集团用户名称
            setCommonAttrValue(sceneInstId, "group_user_name", kitePosDTO.getUsers().get(0).getName(),
                kitePosDTO.getUsers().get(0).getName(), kitePosDTO.getUsers().get(0).getName());
            // 用户归属地
            String userLocation;
            String userLocationName;
            if (KiteStringUtils.isNotEmpty(users.get(0).getProvinceCode())) {
                List<String> regionCodeList = new ArrayList<>(3);
                regionCodeList.add(users.get(0).getProvinceCode());

                if (KiteStringUtils.isNotEmpty(users.get(0).getCityCode())) {
                    regionCodeList.add(users.get(0).getCityCode());

                    if (KiteStringUtils.isNotEmpty(users.get(0).getDistrictCode())) {
                        regionCodeList.add(users.get(0).getDistrictCode());
                    }
                }

                userLocation = regionCodeList.stream().collect(Collectors.joining(SymbolConsts.COMMA));
                userLocationName = LocalAttrHelper.getRegionNames(regionCodeList, SymbolConsts.HYPHEN);
            } else {
                Map<String, String> map = getUserLocation(kitePosDTO);
                userLocation = map.get("userLocation");
                userLocationName = map.get("userLocationName");
            }
            setCommonAttrValue(sceneInstId, "user_location", userLocation, userLocationName, userLocation);

            // 缴费周期 改造计费周期、付费类型、计费类型、缴费周期、账务周期放在user节点传给订单中心
            List<KiteAttrValue> paymentAttrValues = Optional
                .ofNullable(
                    querySceneCommonService.getCommonAttr(sceneInstId, "ORD10233").getResultObject())
                .map(KiteAttr::getAttrValues).orElse(Lists.newArrayList());
            String paymentCycleDesc = transAttrValueDesc(paymentAttrValues, users.get(0).getFeeCycle());
            setCommonAttrValue(sceneInstId, LocalKeyConsts.PAYMENT_CYCLE, users.get(0).getFeeCycle(), paymentCycleDesc,
                users.get(0).getFeeCycle());
            // 账务周期
            List<KiteAttrValue> accountAttrValues = Optional
                .ofNullable(
                    querySceneCommonService.getCommonAttr(sceneInstId, "ORD10234").getResultObject())
                .map(KiteAttr::getAttrValues).orElse(Lists.newArrayList());
            String accountDesc = transAttrValueDesc(accountAttrValues, users.get(0).getAccountCycle());
            setCommonAttrValue(sceneInstId, LocalKeyConsts.ACCOUNT_CYCLE, users.get(0).getAccountCycle(),
                accountDesc, users.get(0).getAccountCycle());
            // 计费周期
            List<KiteAttrValue> chargeAttrValues = Optional
                .ofNullable(
                    querySceneCommonService.getCommonAttr(sceneInstId, "ORD10235").getResultObject())
                .map(KiteAttr::getAttrValues).orElse(Lists.newArrayList());
            String chargeCycleDesc = transAttrValueDesc(chargeAttrValues, users.get(0).getChargeCycle());
            setCommonAttrValue(sceneInstId, LocalKeyConsts.BILL_CYCLE, users.get(0).getChargeCycle(), chargeCycleDesc,
                users.get(0).getChargeCycle());
            // 计费类型
            List<KiteAttrValue> billAttrValues = Optional
                .ofNullable(
                    querySceneCommonService.getCommonAttr(sceneInstId, "ORD10240").getResultObject())
                .map(KiteAttr::getAttrValues).orElse(Lists.newArrayList());
            String billTypeDesc = transAttrValueDesc(billAttrValues, users.get(0).getBillType());
            setCommonAttrValue(sceneInstId, LocalKeyConsts.BILL_TYPE, users.get(0).getBillType(), billTypeDesc,
                users.get(0).getBillType());
            // 付费类型
            List<KiteAttrValue> payAttrValues = Optional
                .ofNullable(
                    querySceneCommonService.getCommonAttr(sceneInstId, "ORD10236").getResultObject())
                .map(KiteAttr::getAttrValues).orElse(Lists.newArrayList());
            String payModeDesc = transAttrValueDesc(payAttrValues, users.get(0).getPayMode());
            setCommonAttrValue(sceneInstId, LocalKeyConsts.CHARGE_TYPE, users.get(0).getPayMode(),
                payModeDesc, users.get(0).getPayMode());

            List<KitePosAttrDTO> userAttrs = users.get(0).getAttrs();
            if (KiteListUtils.isNotEmpty(userAttrs)) {
                String industry = "";
                String industryCode = "";
                String productLine = "";
                String productLineCode = "";
                String segmentKeyProduct = "";
                String segmentKeyProductCode = "";
                KitePosAttrDTO businessIdAttr = userAttrs.stream().filter(
                    attr -> KiteStringUtils.equals(LocalKeyConsts.BUSINESS_NEW, attr.getCode()) || KiteStringUtils
                        .equals(LocalKeyConsts.BUSINESS, attr.getCode())).findFirst().orElse(null);
                String businessId = "";
                if (Objects.nonNull(businessIdAttr)) {
                    businessId = businessIdAttr.getValue();
                }
                for (KitePosAttrDTO userAttr : userAttrs) {
                    // 客户经理公共属性
                    if (KiteStringUtils.equals(LocalKeyConsts.CUST_MANAGER_NAME, userAttr.getCode()) || KiteStringUtils
                        .equals(LocalKeyConsts.CUST_MANAGER_NAME_NEW, userAttr.getCode())) {
                        setCommonAttrValue(sceneInstId, userAttr.getCode(), userAttr.getValue(), userAttr.getValue(),
                            getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_ITEM.toString(),
                                userAttr.getCode()));
                    }
                    if (KiteStringUtils.equals(LocalKeyConsts.CUST_MANAGER_PHONE, userAttr.getCode()) || KiteStringUtils
                        .equals(LocalKeyConsts.CUST_MANAGER_PHONE_NEW, userAttr.getCode())) {
                        setCommonAttrValue(sceneInstId, userAttr.getCode(), userAttr.getValue(), userAttr.getValue(),
                            getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_ITEM.toString(),
                                userAttr.getCode()));
                    }
                    if (KiteStringUtils.equals(LocalKeyConsts.CUST_MANAGER_EMAIL, userAttr.getCode()) || KiteStringUtils
                        .equals(LocalKeyConsts.CUST_MANAGER_EMAIL_NEW, userAttr.getCode())) {
                        setCommonAttrValue(sceneInstId, userAttr.getCode(), userAttr.getValue(), userAttr.getValue(),
                            getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_ITEM.toString(),
                                userAttr.getCode()));
                    }
                    if (KiteStringUtils.equals(LocalKeyConsts.INDUSTRY, userAttr.getCode()) || KiteStringUtils
                        .equals(LocalKeyConsts.INDUSTRY_NEW, userAttr.getCode())) {
                        industry = userAttr.getValue();
                        industryCode = userAttr.getCode();
                    }
                    if (KiteStringUtils.equals(LocalKeyConsts.PRODUCT_LINE, userAttr.getCode()) || KiteStringUtils
                        .equals(LocalKeyConsts.PRODUCT_LINE_NEW, userAttr.getCode())) {
                        productLine = userAttr.getValue();
                        productLineCode = userAttr.getCode();
                    }
                    if (KiteStringUtils.equals(LocalKeyConsts.SEGMENT_KEY_PRODUCT, userAttr.getCode())
                        || KiteStringUtils.equals(LocalKeyConsts.SEGMENT_KEY_PRODUCT_NEW, userAttr.getCode())) {
                        segmentKeyProduct = userAttr.getValue();
                        segmentKeyProductCode = userAttr.getCode();
                    }
                    // 是否总部收费
                    if (KiteStringUtils.equals(LocalKeyConsts.IS_LEADER_CHARGE, userAttr.getCode()) || KiteStringUtils
                        .equals(LocalKeyConsts.IS_LEADER_CHARGE_NEW, userAttr.getCode())) {
                        String fieldName = LocalKeyConsts.IS_LEADER_CHARGE;
                        KiteAttr kiteAttr = querySceneCommonService.getCommonAttr(sceneInstId, fieldName)
                            .getResultObject();
                        if (Objects.isNull(kiteAttr)) {
                            fieldName = LocalKeyConsts.IS_LEADER_CHARGE_NEW;
                            kiteAttr = querySceneCommonService.getCommonAttr(sceneInstId, fieldName).getResultObject();
                        }
                        if (Objects.nonNull(kiteAttr)) {
                            List<KiteAttrValue> feeAttrValues = kiteAttr.getAttrValues();
                            // 判断是否需要真正转换
                            KiteAttrValue flagValue = feeAttrValues.stream().filter(feeAttr -> ("1_0000106".equals(feeAttr.getAttrValue()) || "1_0000107".equals(feeAttr.getAttrValue()))).findFirst().orElse(null);
                            // 订单中心返回0/1，和销售中心枚举值不同，进行特殊处理
                            String value = userAttr.getValue();
                            if (KiteStringUtils.equals("1", value) && (KiteStringUtils
                                .equals(LocalKeyConsts.IS_LEADER_CHARGE, userAttr.getCode()) || Objects.nonNull(flagValue))) {
                                value = "1_0000106";
                            } else if (KiteStringUtils.equals("0", value) && (KiteStringUtils
                                .equals(LocalKeyConsts.IS_LEADER_CHARGE, userAttr.getCode()) || Objects.nonNull(flagValue))) {
                                value = "1_0000107";
                            }
                            String feeCycleDesc = transAttrValueDesc(feeAttrValues, value);
                            setCommonAttrValue(sceneInstId, fieldName, value, feeCycleDesc, value);
                        }
                    }
                    //缴费周期开始时间
                    if (KiteStringUtils.equals(LocalKeyConsts.PAYMENT_CYCLE_START_DATE, userAttr.getCode())) {
                        String fieldName = LocalKeyConsts.PAYMENT_CYCLE_START_DATE;
                        KiteAttr kiteAttr = querySceneCommonService.getCommonAttr(sceneInstId, fieldName)
                            .getResultObject();
                        if (Objects.nonNull(kiteAttr)) {
                            String value = userAttr.getValue();
                            setCommonAttrValue(sceneInstId, fieldName, value, value, value);
                        }
                    }
                    //缴费周期截止时间
                    if (KiteStringUtils.equals(LocalKeyConsts.PAYMENT_CYCLE_END_DATE, userAttr.getCode())) {
                        String fieldName = LocalKeyConsts.PAYMENT_CYCLE_END_DATE;
                        KiteAttr kiteAttr = querySceneCommonService.getCommonAttr(sceneInstId, fieldName)
                            .getResultObject();
                        if (Objects.nonNull(kiteAttr)) {
                            String value = userAttr.getValue();
                            setCommonAttrValue(sceneInstId, fieldName, value, value, value);
                        }
                    }
                    //是否执行信控
                    if (KiteStringUtils.equals(LocalKeyConsts.IS_EXCUTE_INFORMATIONCONTROL, userAttr.getCode())) {
                        String fieldName = LocalKeyConsts.IS_EXCUTE_INFORMATIONCONTROL;
                        KiteAttr kiteAttr = querySceneCommonService.getCommonAttr(sceneInstId, fieldName)
                            .getResultObject();
                        if (Objects.isNull(kiteAttr)) {
                            fieldName = LocalKeyConsts.IS_EXCUTE_INFORMATIONCONTROL;
                            kiteAttr = querySceneCommonService.getCommonAttr(sceneInstId, fieldName).getResultObject();
                        }
                        if (Objects.nonNull(kiteAttr)) {
                            String excuteAttrDesc = transAttrValueDesc(kiteAttr.getAttrValues(), userAttr.getValue());
                            setCommonAttrValue(sceneInstId, fieldName, userAttr.getValue(), excuteAttrDesc,
                                userAttr.getValue());
                        }
                    }

                    // 是否总部直签
                    if (KiteStringUtils.equals(LocalKeyConsts.IS_LEADER_SIGN, userAttr.getCode()) || KiteStringUtils
                        .equals(LocalKeyConsts.IS_LEADER_SIGN_NEW, userAttr.getCode())) {
                        String fieldName = LocalKeyConsts.IS_LEADER_SIGN;
                        KiteAttr kiteAttr = querySceneCommonService.getCommonAttr(sceneInstId, fieldName)
                            .getResultObject();
                        if (Objects.isNull(kiteAttr)) {
                            fieldName = LocalKeyConsts.IS_LEADER_SIGN_NEW;
                            kiteAttr = querySceneCommonService.getCommonAttr(sceneInstId, fieldName).getResultObject();
                        }
                        if (Objects.nonNull(kiteAttr)) {
                            String accountCycleDesc = transAttrValueDesc(kiteAttr.getAttrValues(), userAttr.getValue());
                            setCommonAttrValue(sceneInstId, fieldName, userAttr.getValue(), accountCycleDesc,
                                userAttr.getValue());
                        }
                    }

                    // 是否VIK
                    if (KiteStringUtils.equals(LocalKeyConsts.IS_VIK, userAttr.getCode()) || KiteStringUtils
                        .equals(LocalKeyConsts.IS_VIK_NEW, userAttr.getCode())) {
                        KiteAttr isVikAttr = querySceneCommonService.getCommonAttr(sceneInstId, LocalKeyConsts.IS_VIK_NEW).getResultObject();
                        if (Objects.isNull(isVikAttr)) {
                            isVikAttr = querySceneCommonService.getCommonAttr(sceneInstId, LocalKeyConsts.IS_VIK).getResultObject();
                        }
                        if (Objects.nonNull(isVikAttr)) {
                            String attrValueDesc = transAttrValueDesc(isVikAttr.getAttrValues(), userAttr.getValue());
                            setCommonAttrValue(sceneInstId, userAttr.getCode(), userAttr.getValue(),
                                attrValueDesc, userAttr.getValue());
                            // 优先加载 VIK业务单编码 后再联动处理
                            KitePosAttrDTO vikBusinessCode = userAttrs.stream().filter(attr -> (KiteStringUtils.equals(LocalKeyConsts.VIK_BUSINESS_CODE, attr.getCode()) ||
                                KiteStringUtils.equals(LocalKeyConsts.VIK_BUSINESS_CODE_NEW, attr.getCode()))).findFirst().orElse(null);
                            if (Objects.nonNull(vikBusinessCode)) {
                                setCommonAttrValue(sceneInstId, vikBusinessCode.getCode(), vikBusinessCode.getValue(),
                                    vikBusinessCode.getValue(), vikBusinessCode.getValue());
                            }
                            // 有联动
                            personAttrDealService.apply(sceneInstId, userAttr.getCode(), userAttr.getValue(),
                                Optional.ofNullable(attrValueDesc).orElse(userAttr.getValue()), isVikAttr.getModuleId());
                        }
                    }
                    // 商机
                    List<QryIOTOppoDockingSalesRsp> iotoOppoList = new ArrayList<>();
                    if (KiteStringUtils.equals(LocalKeyConsts.BUSINESS, userAttr.getCode()) || KiteStringUtils
                        .equals(LocalKeyConsts.BUSINESS_NEW, userAttr.getCode())) {
                        setCommonAttrValue(sceneInstId, userAttr.getCode(), businessId, businessId, businessId);
                        // 兼容老用户
                        List<KitePosAttrDTO> businessUserAttr = userAttrs.stream().filter(
                            business -> KiteStringUtils.equals(LocalKeyConsts.BUSINESS_NAME, business.getCode()))
                            .collect(Collectors.toList());
                        if (KiteListUtils.isEmpty(businessUserAttr)) {
                            String businessName = "";
                            //String custId = kitePosDTO.getCustomer().getCustId();
                            String contextCustId = KiteStringUtils.isEmpty(ContextUtil.getHttpSessoinId()) ? custId
                                : KiteWebContext.getKiteContextId();
                            CuccContextCustDTO custDTO = KiteContextCache
                                .get(KiteStringUtils.joinWith(SymbolConsts.AT, contextCustId, "custInfo"));
                            iotoOppoList = infServiceBus.queryIOTOppoDockingSales(
                                KiteObjectUtils.isEmpty(custDTO) || KiteStringUtils.isEmpty(custDTO.getCbssId()) ?
                                    custId :
                                    custDTO.getCbssId());
                            for (QryIOTOppoDockingSalesRsp iotoOppo : iotoOppoList) {
                                if (KiteStringUtils.equals(businessId, iotoOppo.getOppoNumber())) {
                                    businessName = iotoOppo.getOppoName();
                                }
                            }
                            setCommonAttrValue(sceneInstId, "ORD10170", businessName, businessName, businessName);
                        }
                    }
                    if (KiteStringUtils.equals(LocalKeyConsts.BUSINESS_NAME, userAttr.getCode()) || KiteStringUtils
                        .equals(LocalKeyConsts.BUSINESS_NAME_NEW, userAttr.getCode())) {
                        String businessName = userAttr.getValue();
                        if (KiteStringUtils.isEmpty(businessName)) {
                            //String custId = kitePosDTO.getCustomer().getCustId();
                            if (KiteListUtils.isEmpty(iotoOppoList)) {
                                iotoOppoList = infServiceBus.queryIOTOppoDockingSales(custId);
                            }
                            for (QryIOTOppoDockingSalesRsp iotoOppo : iotoOppoList) {
                                if (KiteStringUtils.equals(businessId, iotoOppo.getOppoNumber())) {
                                    businessName = iotoOppo.getOppoName();
                                }
                            }
                        }
                        setCommonAttrValue(sceneInstId, userAttr.getCode(), businessName, businessName, businessName);
                    }
                    // 售前信息处理
                    if (KiteStringUtils.equals(LocalKeyConsts.CHECK_NUMBER, userAttr.getCode())) {
                        setCommonAttrValue(sceneInstId, userAttr.getCode(), userAttr.getValue(),
                            userAttr.getValue(), userAttr.getValue());
                    }
                    if (KiteStringUtils.equals(LocalKeyConsts.DISCOUNT_ORDER_NUMBER, userAttr.getCode())) {
                        setCommonAttrValue(sceneInstId, userAttr.getCode(), userAttr.getValue(),
                            userAttr.getValue(), userAttr.getValue());
                    }
                    if (KiteStringUtils.equals(LocalKeyConsts.OPPORTUNITY_NUMBER, userAttr.getCode())) {
                        setCommonAttrValue(sceneInstId, userAttr.getCode(), userAttr.getValue(),
                            userAttr.getValue(), userAttr.getValue());
                    }
                    if (KiteStringUtils.equals(LocalKeyConsts.PRE_ASSESSMENT, userAttr.getCode())) {
                        setCommonAttrValue(sceneInstId, userAttr.getCode(), userAttr.getValue(),
                            userAttr.getValue(), userAttr.getValue());
                    }
                    if (KiteStringUtils.equals(LocalKeyConsts.AGREEMENT_NUMBER, userAttr.getCode())) {
                        setCommonAttrValue(sceneInstId, userAttr.getCode(), userAttr.getValue(),
                            userAttr.getValue(), userAttr.getValue());
                    }
                }
                // 行业、产品线、细分重点产品
                IIndustryService industryService = KiteSpringUtils.getBeanHighPriority(IIndustryService.class);
                List<KiteIndustryConfig> kiteIndustryList = industryService.listSubIndustry("");
                for (KiteIndustryConfig kiteIndustry : kiteIndustryList) {
                    if (KiteStringUtils.equals(industry, kiteIndustry.getIndustryCode())) {
                        KiteAttr resultObject = querySceneCommonService.getCommonAttr(sceneInstId, industryCode)
                            .getResultObject();
                        if (!KiteObjectUtils.isEmpty(resultObject)) {
                            SpringUtil.getBean(IOperateSceneCommonService.class).setCommonAttr(sceneInstId, resultObject);
                        }
                        setCommonAttrValue(sceneInstId, industryCode, kiteIndustry.getIndustryCode(),
                            kiteIndustry.getIndustryName(), kiteIndustry.getIndustryCode());
                    }
                }

                List<KiteIndustryConfig> kiteIndustryListOne = industryService.listSubIndustry(industry);
                for (KiteIndustryConfig kiteIndustry : kiteIndustryListOne) {
                    if (KiteStringUtils.equals(productLine, kiteIndustry.getIndustryCode())) {
                        KiteAttr resultLine = querySceneCommonService.getCommonAttr(sceneInstId, productLineCode)
                            .getResultObject();
                        if (Objects.nonNull(resultLine)) {
                            List<KiteAttrValue> attrValues = resultLine.getAttrValues();
                            KiteAttrValue kiteAttrValue = new KiteAttrValue();
                            kiteAttrValue.setAttrValue(kiteIndustry.getIndustryCode());
                            kiteAttrValue.setAttrValueName(kiteIndustry.getIndustryName());
                            attrValues.add(kiteAttrValue);
                            SpringUtil.getBean(IOperateSceneCommonService.class).setCommonAttr(sceneInstId, resultLine);
                            setCommonAttrValue(sceneInstId, productLineCode, kiteIndustry.getIndustryCode(),
                                kiteIndustry.getIndustryName(), kiteIndustry.getIndustryCode());
                        }
                    }
                }

                List<KiteIndustryConfig> kiteIndustryListTwo = industryService.listSubIndustry(productLine);
                for (KiteIndustryConfig kiteIndustry : kiteIndustryListTwo) {
                    if (KiteStringUtils.equals(segmentKeyProduct, kiteIndustry.getIndustryCode())) {

                        KiteAttr resultKey = querySceneCommonService.getCommonAttr(sceneInstId, segmentKeyProductCode)
                            .getResultObject();
                        if (Objects.nonNull(resultKey)) {
                            List<KiteAttrValue> attrValuesTwo = resultKey.getAttrValues();
                            KiteAttrValue kiteAttrValueTwo = new KiteAttrValue();
                            kiteAttrValueTwo.setAttrValue(kiteIndustry.getIndustryCode());
                            kiteAttrValueTwo.setAttrValueName(kiteIndustry.getIndustryName());
                            attrValuesTwo.add(kiteAttrValueTwo);
                            SpringUtil.getBean(IOperateSceneCommonService.class).setCommonAttr(sceneInstId, resultKey);
                            setCommonAttrValue(sceneInstId, segmentKeyProductCode, kiteIndustry.getIndustryCode(),
                                kiteIndustry.getIndustryName(), kiteIndustry.getIndustryCode());
                        }
                    }
                }
            }
        }
        List<KiteAttr> commonAttrs = this.querySceneInstService.listCommonAttrs(sceneInstId);
        //经办人公共属性
        KitePosOperatorDTO operator = kitePosDTO.getOperator();
        if (Objects.nonNull(operator)) {
            this.operateSceneInstService
                .putExtParameter(sceneInstId, LocalKeyConsts.HANDLER_INFO_NAME, operator.getName());

            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.HANDLER_INFO_NAME, operator.getName(), operator.getName(),
                "", commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.HANDLER_INFO_ADDRESS, operator.getAddress(),
                operator.getAddress(), "", commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.HANDLER_INFO_SATISFACTION, operator.getCustSatisfaction(),
                operator.getCustSatisfaction(), "", commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.HANDLER_INFO_EMAIL, operator.getEmail(), operator.getEmail(),
                "", commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.HANDLER_INFO_FAXNUM, operator.getFax(), operator.getFax(),
                "", commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.HANDLER_INFO_FIXEDPHONE, operator.getFixedPhone(),
                operator.getFixedPhone(), "", commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.HANDLER_INFO_CARDNUM, operator.getIdNo(), operator.getIdNo(),
                "", commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.HANDLER_INFO_CARDTYPE, operator.getIdType(),
                operator.getIdType(), "", commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.HANDLER_INFO_POSTCODE, operator.getPostcode(),
                operator.getPostcode(), "", commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.HANDLER_INFO_COMMENTS, operator.getRemark(),
                operator.getRemark(), "", commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.HANDLER_INFO_SEX, operator.getSex(), operator.getSex(), "", commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.HANDLER_INFO_TEL, operator.getPhone(), operator.getPhone(),
                "", commonAttrs);
            List<KitePosAttachmentDTO> attachments = operator.getAttachments();
            if (!KiteListUtils.isEmpty(attachments)) {
                List<AttachmentVO> attachements = new ArrayList<>();
                for (KitePosAttachmentDTO attachement : attachments) {
                    AttachmentVO attachmentVO = new AttachmentVO();
                    attachmentVO.setAttachmentUrl(attachement.getUrl());
                    attachmentVO.setFileName(attachement.getName());
                    attachements.add(attachmentVO);
                }
                for (KitePosAttachmentDTO attachement : attachments) {
                    this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.HANDLER_INFO_ATTACHMENTS,
                        JSONObject.toJSONString(attachements), attachement.getName(), "", commonAttrs);
                }
            }

            // 若订单来源不是销售中心，order节点下没有 HandlerCustInfo 属性，导致有operator经办人节点却不会勾选，用经办人名称判断
            if(Objects.nonNull(kitePosDTO.getRequest()) && !KiteStringUtils.isEqual(kitePosDTO.getRequest().getSourceMall(), "24")) {
                // 已选经办人，设置为选中
                if (KiteStringUtils.isNotEmpty(operator.getName())) {
                    this.setCommonAttrValueToList(sceneInstId, "HandlerCustInfo", "T", "T", "T", commonAttrs);
                }
            }
        }
        //发展人公共属性
        KitePosDeveloperDTO developer = kitePosDTO.getDeveloper();
        if (Objects.nonNull(developer) && !KiteStringUtils.equalsAny(serviceOfferId, "1082", "1083")) {
            this.operateSceneInstService.putExtParameter(sceneInstId, "developer", developer);
            String chnlIdOriginValue = getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_DEVELOP.toString(),
                "DEVELOP_DEPART_ID");
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.DEVPERSON_INFO_CHANNELID, developer.getChannelId(),
                developer.getChannelId(), chnlIdOriginValue, commonAttrs);
            String chnlName = developer.getChannelName();
            if (KiteStringUtils.isEmpty(chnlName)) {
                // 调接口查询发展人渠道名称
                String channelId = developer.getChannelId();
                chnlName = CuccChannelCache.getChannelName(channelId);
            }
            String chnlNameOriginValue = chnlName;
            if (!KiteStringUtils.equals(chnlIdOriginValue, developer.getChannelId())) {
                chnlNameOriginValue = CuccChannelCache.getChannelName(chnlIdOriginValue);
            }
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.DEVPERSON_INFO_CHANNELNAME, chnlName, chnlName,
                chnlNameOriginValue, commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.DEVPERSON_INFO_NAME, developer.getName(),
                developer.getName(),
                getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_DEVELOP.toString(), "DEVELOP_STAFF_NAME"), commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.DEVPERSON_INFO_ID, developer.getStaffId(),
                developer.getStaffId(),
                getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_DEVELOP.toString(), "DEVELOP_STAFF_ID"), commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.DEVPERSON_INFO_TEL, developer.getPhone(),
                developer.getPhone(),
                getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_DEVELOP.toString(), "DEVELOP_CONTACT"), commonAttrs);
            String isSendSms = getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_DEVELOP.toString(),
                "isSendSms");
            if (KiteStringUtils.isEmpty(isSendSms)) {
                isSendSms = "0";
            }
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.DEVPERSON_INFO_SENDMESSAGE, developer.getIsSendSms(),
                developer.getIsSendSms(), isSendSms, commonAttrs);
            // 已选发展人，设置为选中
            if (!KiteStringUtils.isEmpty(chnlName)) {
                this.setCommonAttrValueToList(sceneInstId, "devPersonInfo", "T",
                    "T", "T", commonAttrs);
            }

        }
        //联系人公共属性
        KitePosLinkmanDTO linkman = kitePosDTO.getLinkman();
        if (Objects.nonNull(linkman)) {
            this.operateSceneInstService.putExtParameter(sceneInstId, "linkman", linkman);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.CONTACT_INFO_NAME, linkman.getName(), linkman.getName(),
                getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_CONTACT.toString(), "CONTACT_NAME"), commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.CONTACT_INFO_TEL, linkman.getPhone(), linkman.getPhone(),
                getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_CONTACT.toString(), "CONTACT_MOBILE"), commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.CONTACT_INFO_EMAIL, linkman.getEmail(), linkman.getEmail(),
                getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_CONTACT.toString(), "CONTACT_EMAIL"), commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.CONTACT_INFO_ADDRESS, linkman.getAddress(),
                linkman.getAddress(),
                getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_CONTACT.toString(), "CONTACT_ADDR"), commonAttrs);
            String linkCardTypeAttrId = "";
            for (KiteAttr commonAttr : commonAttrs) {
                if (KiteStringUtils.equals(LocalKeyConsts.CONTACT_INFO_CARDTYPE, commonAttr.getFieldName())) {
                    linkCardTypeAttrId = commonAttr.getAttrId();
                }
            }
            String linkmanValueDesc = Optional.ofNullable(AttrValueCache.getAttrValue(linkCardTypeAttrId, linkman.getPersonIdType()))
                .map(AttrValue::getAttrValueName).orElse(linkman.getPersonIdType());
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.CONTACT_INFO_CARDTYPE, linkman.getPersonIdType(),
                linkmanValueDesc,
                getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_CONTACT.toString(),
                    "LICENCE_TYPE"), commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.CONTACT_INFO_CARDNUM, linkman.getPersonNum(),
                linkman.getPersonNum(),
                getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_CONTACT.toString(), "LICENCE_NUMBER"), commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.CONTACT_INFO_FIXEDPHONE, linkman.getFixedPhone(),
                linkman.getFixedPhone(),
                getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_CONTACT.toString(), "CONTACT_PHONE"), commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.CONTACT_INFO_FAXNUM, linkman.getFax(), linkman.getFax(),
                getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_CONTACT.toString(), "CONTACT_FAX"), commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.CONTACT_INFO_POSTCODE, linkman.getPostcode(),
                linkman.getPostcode(), getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_CONTACT.toString(),
                    "CONTACT_POSTCODE"), commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.CONTACT_INFO_COMMENTS, linkman.getRemark(),
                linkman.getRemark(), getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_CONTACT.toString(),
                    LocalKeyConsts.CONTACT_INFO_COMMENTS), commonAttrs);

            if (!KiteStringUtils.isEmpty(linkman.getName())) {
                this.setCommonAttrValueToList(sceneInstId, "contactInfo", "T",
                    "T", "T", commonAttrs);
            }

        }
        //代理人
        KitePosOrderDTO kitePosOrderDTO = kitePosDTO.getOrder();
        List<KitePosAttrDTO> orderAttrs = Objects.nonNull(kitePosOrderDTO) ?
            kitePosOrderDTO.getAttrs() :
            new ArrayList<>();
        KitePosAttrDTO orderkiteAttr= orderAttrs.stream().filter(kiteattr ->"ORD10293".equals(kiteattr.getCode())&&!KiteStringUtils.isEmpty(kiteattr.getValue())).findFirst().orElse(null);
        if(!KiteObjectUtils.isEmpty(orderkiteAttr)){
            registrationService.registrationDetail(ContextUtil.getLoginInfo().getStaffInfo().getStaffCode(),orderkiteAttr.getValue(),sceneInstId,commonAttrs);
        }
        List<KitePosAttrDTO> agentAttrs = orderAttrs.stream().filter((attr) -> "agent".equals(attr.getCode()))
            .collect(Collectors.toList());
        if (KiteListUtils.isEmpty(agentAttrs)) {
            List<KitePosUserDTO> kitePosDTOUsers = kitePosDTO.getUsers();
            List<KitePosAttrDTO> userAllAttrs = KiteListUtils.isEmpty(kitePosDTOUsers) ?
                new ArrayList<>() :
                kitePosDTOUsers.get(0).getAttrs();
            if (!KiteListUtils.isEmpty(userAllAttrs)) {
                agentAttrs = userAllAttrs.stream().filter((attr) -> "agent".equals(attr.getCode()))
                    .collect(Collectors.toList());
            }
        }
        if (!KiteListUtils.isEmpty(agentAttrs)) {
            KitePosAttrDTO agentAttr = agentAttrs.get(0);
            KitePosAgentDTO agentDto = JSON.parseObject(agentAttr.getValue(), KitePosAgentDTO.class);
            if (!KiteStringUtils.equals("{}", agentAttr.getValue())) {
                this.operateSceneInstService.putExtParameter(sceneInstId, "agent", agentDto);
            }
            String channelIdOriginValue = getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_AGNET.toString(),
                "AGENT_CHNL_CODE");
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.AGENT_INFO_CHANNELID, agentDto.getAgentChannelId(),
                agentDto.getAgentChannelId(), channelIdOriginValue, commonAttrs);
            String chnlName = agentDto.getAgentChannelName();
            if (KiteStringUtils.isEmpty(chnlName)) {
                // 调接口查询发展人渠道名称
                String channelId = agentDto.getAgentChannelId();
                chnlName = CuccChannelCache.getChannelName(channelId);
            }
            String chnlNameOriginValue = chnlName;
            if (!KiteStringUtils.isEqual(channelIdOriginValue, agentDto.getAgentChannelId())) {
                chnlNameOriginValue = CuccChannelCache.getChannelName(channelIdOriginValue);
            }
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.AGENT_INFO_CHANNELNAME, chnlName, chnlName,
                chnlNameOriginValue, commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.AGENT_INFO_CARDTYPE, agentDto.getAgentIdType(),
                agentDto.getAgentIdType(), getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_AGNET.toString(),
                    LocalKeyConsts.AGENT_INFO_CARDTYPE), commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.AGENT_INFO_CARDNUM, agentDto.getAgentIdNo(),
                agentDto.getAgentIdNo(), getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_AGNET.toString(),
                    LocalKeyConsts.AGENT_INFO_CARDNUM), commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.AGENT_INFO_CARDADDRESS, agentDto.getAgentAddress(),
                agentDto.getAgentAddress(),
                getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_AGNET.toString(),
                    LocalKeyConsts.AGENT_INFO_CARDADDRESS), commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.AGENT_INFO_ID, agentDto.getAgentId(), agentDto.getAgentId(),
                getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_AGNET.toString(),
                    LocalKeyConsts.AGENT_INFO_ID), commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.AGENT_INFO_NAME, agentDto.getAgentName(),
                agentDto.getAgentName(), getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_AGNET.toString(),
                    LocalKeyConsts.AGENT_INFO_NAME), commonAttrs);
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.AGENT_INFO_TEL, agentDto.getAgentPhone(),
                agentDto.getAgentPhone(),
                getCommonInfoOriginValue(userDetail, UserDetailTagName.USER_AGNET.toString(), "AGENT_CONTACT"), commonAttrs);
            operateSceneInstService.putExtParameter(sceneInstId, "channelId", agentDto.getAgentChannelId());
        }
        //如果有退单原因
        Map backReason = (Map) loginInfo.getUserInfo().getExtParams().get("BackReason");
        if(Objects.nonNull(backReason)){
            String backResonStr = KiteMapUtils.getString(backReason,"failReason");
            this.setCommonAttrValueToList(sceneInstId, "BackReason",backResonStr ,
                backResonStr, backResonStr, commonAttrs);
            //setCommonAttrValue(sceneInstId, "BackReason", backReason.getFailReason(), backReason.getFailReason(), backReason.getFailReason());
        }
        //附件
        List<KitePosAttachmentDTO> attachements = Objects.nonNull(kitePosOrderDTO) ?
            kitePosOrderDTO.getAttachments() :
            new ArrayList<>();
        if (!KiteListUtils.isEmpty(attachements)) {
            List<Map<String, String>> valueList = new ArrayList<>();
            for (KitePosAttachmentDTO attachement : attachements) {
                Map<String, String> dataMap = new HashMap<>();
                dataMap.put("attachmentUrl", attachement.getUrl());
                dataMap.put("fileType", "ATTACHMENTS_TYPE_" + attachement.getCatagory());
                dataMap.put("fileName", attachement.getName());
                dataMap.put("createDate", attachement.getUploadTime());
                // 二次类业务，从商品中心获取出来的数据，表示为K，为了预览页面做变动计算用。
                if (KiteStringUtils.isNotEmpty(attachement.getChangeType())) {
                    dataMap.put("originValue", ChangeTypeUtils.getActionType(attachement.getChangeType()).name());
                    dataMap.put("actionType", ChangeTypeUtils.getActionType(attachement.getChangeType()).name());
                } else {
                    dataMap.put("actionType", KeyConsts.ACTION_TYPE_K);
                    dataMap.put("originValue", KeyConsts.ACTION_TYPE_K);
                }
                valueList.add(dataMap);
            }

            // 附件及备注（止租信息里也有附件，赋值会造成干扰，此处以 module_id=94 进行过滤）
            List<KiteAttr> attachmentAttrs = commonAttrs.stream().filter(attr -> KiteStringUtils.equals("94", attr.getModuleId())).collect(Collectors.toList());
            if(KiteListUtils.isEmpty(attachmentAttrs)) {
                attachmentAttrs = commonAttrs;
            }
            this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.COMMON_ATTR_KEY_ATTACHMENT, JSON.toJSONString(valueList),
                JSON.toJSONString(valueList), JSON.toJSONString(valueList), attachmentAttrs);
        }
        String remark = Objects.nonNull(kitePosOrderDTO) ? kitePosOrderDTO.getRemark() : "";
        //备注
        this.setCommonAttrValueToList(sceneInstId, LocalKeyConsts.COMMON_ATTR_KEY_REMARK, remark, remark, remark, commonAttrs);
        // 批量更新
        operateSceneInstService.setCommonAttrs(sceneInstId, commonAttrs);
        //其他订单/业务属性
        // 过滤经办人附件属性，防止重复赋值
        orderAttrs.removeIf(orderAttr -> "handler_info_attachments".equals(orderAttr.getCode()));
        orderAttrs.forEach(attr -> {
            KiteAttr kiteAttr = this.querySceneInstService.getCommonAttr(sceneInstId, attr.getCode());
            if (Objects.nonNull(kiteAttr)) {
                String attrValueDesc = null;
                if (!KiteListUtils.isEmpty(kiteAttr.getAttrValues())) {
                    List<KiteAttrValue> kiteAttrValues = kiteAttr.getAttrValues().stream()
                        .filter(attrValueStr -> KiteStringUtils.equals(attrValueStr.getAttrValue(), attr.getValue()))
                        .collect(Collectors.toList());
                    if (!KiteListUtils.isEmpty(kiteAttrValues)) {
                        attrValueDesc = kiteAttrValues.get(0).getAttrValueName();
                    }
                }
                // 设置OriginValue值,order节点下的联系人、发展人信息不能作为originValue
                KiteAttr commonAttr = commonAttrs.stream()
                    .filter(attr1 -> !KiteStringUtils.equalsAny(attr1.getModuleId(), LocalKeyConsts.MODULE_ID_CONTACT, LocalKeyConsts.MODULE_ID_DEVELOPER, "140"))
                    .filter(attr1 -> KiteStringUtils.equals(attr.getCode(), attr1.getFieldName()))
                    .findFirst().orElse(null);
                if (Objects.nonNull(commonAttr)) {
                    commonAttr.setValue(attr.getValue());
                    commonAttr.setOriginValue(attr.getValue());
                    operateSceneInstService.setCommonAttr(sceneInstId, commonAttr);
                }
                //有联动
                personAttrDealService.apply(sceneInstId, attr.getCode(), attr.getValue(),
                    Optional.ofNullable(attrValueDesc).orElse(attr.getValue()), kiteAttr.getModuleId());
            }else if(LocalKeyConsts.MV_REPLACE_A.equals(attr.getCode())){
                KiteAttr AAttr = commonAttrs.stream()
                    .filter(attr1 -> KiteStringUtils.equals(LocalKeyConsts.REPLACE_A, attr1.getFieldName()))
                    .findFirst().orElse(null);
                if (Objects.nonNull(AAttr)) {
                    AAttr.setValue(attr.getValue());
                    AAttr.setOriginValue(attr.getValue());
                    operateSceneInstService.setCommonAttr(sceneInstId, AAttr);
                }
            }else if(LocalKeyConsts.MV_REPLACE_Z.equals(attr.getCode())){
                KiteAttr ZAttr = commonAttrs.stream()
                    .filter(attr1 -> KiteStringUtils.equals(LocalKeyConsts.REPLACE_Z, attr1.getFieldName()))
                    .findFirst().orElse(null);
                if (Objects.nonNull(ZAttr)) {
                    ZAttr.setValue(attr.getValue());
                    ZAttr.setOriginValue(attr.getValue());
                    operateSceneInstService.setCommonAttr(sceneInstId, ZAttr);
                }
            }

        });
    }

    // 查询用户公用信息原始数据
    private Map<String, Object> queryCommonInfoOriginValue(LoginInfo loginInfo, List<KitePosUserDTO> users, String sceneInstId, String serviceOfferId) {
        if (KiteListUtils.isEmpty(users)) {
            return new HashMap<String, Object>();
        }
        if (KiteStringUtils.equalsAny(serviceOfferId, ServiceOfferConsts.SERVICE_OFFER_ORDER,
            LocalServiceOfferConsts.SERVICE_OFFER_RESOURCE_CHECK, LocalServiceOfferConsts.SERVICE_OFFER_TRANSFER_TO_ORDER,
            LocalServiceOfferConsts.SERVICE_OFFER_ADD_ORDER, LocalServiceOfferConsts.SERVICE_OFFER_ORDER_OPPER)) {
            return new HashMap<String, Object>();
        }
        String bizType = querySceneInstService.getExtParameterValue(sceneInstId, "bizType");
        // 订购、资源核查的特殊处理流程
        if (KiteStringUtils.equalsAny(bizType, "1001", "1012") && KiteStringUtils.equalsAny(serviceOfferId, LocalServiceOfferConsts.SERVICE_OFFER_FOLLOW,
            LocalServiceOfferConsts.SERVICE_OFFER_CANCEL, LocalServiceOfferConsts.SERVICE_OFFER_LOCKORRELEASE,
            LocalServiceOfferConsts.SERVICE_OFFER_URGENTORPOSTPONE)) {
            return new HashMap<String, Object>();
        }

        String accNum = users.get(0).getSerialNumber();
        String userId = users.get(0).getUserId();
        Map<String, Object> inMap = new HashMap<>();
        String staffCode = loginInfo.getStaffInfo().getStaffCode();
        String eparchyCode = KiteStringUtils.isNotEmpty(users.get(0).getCityCode()) ? users.get(0).getCityCode() : loginInfo.getUserInfo().getPostLanId();
        String provinceCode = KiteStringUtils.isNotEmpty(users.get(0).getProvinceCode()) ? users.get(0).getProvinceCode() : loginInfo.getUserInfo().getPostProvinceNbr();
        inMap.put("accNum", accNum);
        inMap.put("userId", userId);
        inMap.put("staffCode", staffCode);
        inMap.put("eparchyCode", eparchyCode);
        inMap.put("provinceCode", provinceCode);
        IInfServiceBus infServiceBus = SpringUtil.getBean(IInfServiceBus.class);
        Map<String, Object> userDetail = infServiceBus.queryUserDetail(inMap, Lists
            .newArrayList(UserDetailTagName.USER_DEVELOP, UserDetailTagName.USER_AGNET, UserDetailTagName.USER_ITEM,
                UserDetailTagName.USER_CONTACT, UserDetailTagName.USER_CONTRACT, UserDetailTagName.USER));
        return userDetail;
    }

    @SuppressWarnings("unchecked")
    private String getCommonInfoOriginValue(Map<String, Object> commonInfo, String commonInfoType, String code) {
        if (KiteMapUtils.isEmpty(commonInfo)) {
            return "";
        }
        List<Map> userInfos = new ArrayList<Map>();
        // 发展人
        if (KiteStringUtils.isEqual(commonInfoType, UserDetailTagName.USER_DEVELOP.toString())) {
            userInfos = (List) commonInfo.get("USER_DEVELOP_INFOS");
        }
        //代理人
        if (KiteStringUtils.isEqual(commonInfoType, UserDetailTagName.USER_AGNET.toString())) {
            userInfos = (List) commonInfo.get("USER_AGENT_INFOS");
        }
        //联系人
        if (KiteStringUtils.isEqual(commonInfoType, UserDetailTagName.USER_CONTACT.toString())) {
            userInfos = (List) commonInfo.get("USER_CONTACT_INFOS");
        }
        //客户经理
        if (KiteStringUtils.isEqual(commonInfoType, UserDetailTagName.USER_ITEM.toString())) {
            userInfos = (List) commonInfo.get("USER_ITEM_INFOS");// 用户属性
        }
        if (KiteListUtils.isEmpty(userInfos)) {
            return "";
        }
        for (Map userInfo : userInfos) {
            if (KiteStringUtils.isEqual(commonInfoType, UserDetailTagName.USER_ITEM.toString())) {
                if (KiteStringUtils.isEqual((String) userInfo.getOrDefault("CRM_ATTR_CODE", ""), code)) {
                    return (String) userInfo.getOrDefault("ATTR_VALUE", "");
                }
            } else {
                String originValue = (String) userInfo.getOrDefault(code, "");
                if (KiteStringUtils.isNotEmpty(originValue)) {
                    return originValue;
                }
            }
        }
        return "";
    }

    public String transAttrValueDesc(List<KiteAttrValue> attrValues, String value) {
        if (KiteListUtils.isNotEmpty(attrValues)) {
            for (KiteAttrValue attrValue : attrValues) {
                if (KiteStringUtils.equals(value, attrValue.getAttrValue())) {
                    value = attrValue.getAttrValueName();
                    return value;
                }
            }
        }
        return value;
    }

    private Map<String, String> getUserLocation(KitePosDTO kitePosDTO) {
        Map<String, String> resultMap = new HashMap<String, String>();
        KitePosOrderDTO orderDto = kitePosDTO.getOrder();
        List<String> regionCodeList = new ArrayList<>(3);
        if (Objects.nonNull(orderDto)) {
            String provinceCode = null;
            String eparchyCode = null;
            String cityCode = null;
            List<KitePosAttrDTO> kiteAttrs = orderDto.getAttrs();
            KitePosAttrDTO provinceAttr = kiteAttrs.stream().filter(attr -> attr.getCode().equals("provinceCode"))
                .findFirst().orElse(null);
            if (Objects.nonNull(provinceAttr)) {
                provinceCode = provinceAttr.getValue();
            }
            KitePosAttrDTO eparchyAttr = kiteAttrs.stream().filter(attr -> attr.getCode().equals("eparchyCode"))
                .findFirst().orElse(null);
            if (Objects.nonNull(eparchyAttr)) {
                eparchyCode = eparchyAttr.getValue();
            }
            KitePosAttrDTO citAttr = kiteAttrs.stream().filter(attr -> attr.getCode().equals("cityCode")).findFirst()
                .orElse(null);
            if (Objects.nonNull(citAttr)) {
                cityCode = citAttr.getValue();
            }

            if (KiteStringUtils.isNotBlank(provinceCode)) {
                regionCodeList.add(provinceCode);

                if (KiteStringUtils.isNotBlank(eparchyCode)) {
                    regionCodeList.add(eparchyCode);

                    if (KiteStringUtils.isNotBlank(cityCode)) {
                        regionCodeList.add(cityCode);
                    }
                }
            }
        }
        resultMap.put("userLocation", regionCodeList.stream().collect(Collectors.joining(SymbolConsts.COMMA)));
        resultMap.put("userLocationName", LocalAttrHelper.getRegionNames(regionCodeList, SymbolConsts.HYPHEN));
        return resultMap;
    }

    @Override
    public void setCommonAttrValue(String sceneInstId, String fieldName, String value, String valueDesc,
                                   String originValue) {
        //没有联动
        commonAttrDealService.apply(sceneInstId, fieldName, value, valueDesc);
        // 设置OriginValue值
        KiteAttr commonAttr = querySceneCommonService.getCommonAttr(sceneInstId, fieldName).getResultObject();
        if (Objects.nonNull(commonAttr)) {
            commonAttr.setOriginValue(originValue);
            operateSceneInstService.setCommonAttr(sceneInstId, commonAttr);
        }
    }

    private void setCommonAttrValueToList(String sceneInstId, String fieldName, String value, String valueDesc,
                                          String originValue, List<KiteAttr> commonAttrs) {
        List<KiteAttr> targetAttrs = commonAttrs.stream().filter(attr -> KiteStringUtils.equals(fieldName, attr.getFieldName())).collect(Collectors.toList());
        if (!KiteListUtils.isEmpty(targetAttrs)) {
            targetAttrs.stream().forEach(targetAttr ->{
                targetAttr.setValue(value);
                targetAttr.setValueDesc(valueDesc);
                targetAttr.setOriginValue(originValue);
            });
        }
    }

    @Override
    public List<Map<String, Object>> queryHandlerInfos(Map<String, Object> map) {
        List<Map<String, Object>> handlerMap = infServiceBus.queryHandlerInfo(map);
        return handlerMap;
    }

    @Override
    public Map<String, Object> queryHandlerFile(String fileKey) {
        Map<String, Object> handlerFile = infServiceBus.queryHandlerFile(fileKey);
        return handlerFile;
    }

    @Override
    public List<CommonAttrVO> saveHandlerInfos(Map<String, Object> map, String sceneInstId) {
        String barCode = "";
        String attchemnetCertType = "";
        String fileKey = "";
        String certName = "";
        String certNum = "";
        String certType = "";
        List<Map> attachmentLists = new ArrayList<>();
        String attachmentDesc = "";

        certType = KiteMapUtils.getString(map, "certType");
        // 经办人证件类型转换
        //certType = DcPublicCache.getCodea("20210615001", certType);
        certName = KiteMapUtils.getString(map, "certName");
        certNum = KiteMapUtils.getString(map, "certNum");
        List<Map> fileLogs = (List<Map>) map.get("fileLogs");
        for (Map fileLog : fileLogs) {
            barCode = KiteMapUtils.getString(fileLog, "BAR_CODE");
            attchemnetCertType = KiteMapUtils.getString(fileLog, "CERT_TYPE");
            fileKey = KiteMapUtils.getString(fileLog, "FILE_KEY");
            // 自然客户附件下载接口 根据fileKey获取附件信息
            Map<String, Object> handlerFile = infServiceBus.queryHandlerFile(fileKey);
            String respCode = KiteMapUtils.getString(handlerFile, "RESP_CODE");
            if (KiteStringUtils.equals("0000", respCode)) {
                String fileName = KiteMapUtils.getString(handlerFile, "FILE_NAME");
                attachmentDesc = fileName;
                String fileContent = KiteMapUtils.getString(handlerFile, "FILE_CONTENT");
                String fileType = KiteStringUtils.substring(fileName, fileName.lastIndexOf('.') + 1);
                // 附件上传接口
                Map<String, Object> uploadResultMap = infServiceBus.orderCenterFileUpload(fileName, fileType, fileContent);
                String fileId = KiteMapUtils.getString(uploadResultMap, "FILE_ID");
                Map<String, Object> attachmentMap = new HashMap<>();
                attachmentMap.put("fileName", fileName);
                attachmentMap.put("attachmentUrl", fileId);
                attachmentMap.put("barCode", barCode);
                attachmentMap.put("source", "1");
                attachmentMap.put("fileType", attchemnetCertType);
                attachmentLists.add(attachmentMap);
            }
        }
        String attachmentValue = JSONObject.toJSONString(attachmentLists);

        saveHandlerValue(sceneInstId, LocalKeyConsts.HANDLER_INFO_NAME, certName, certName, LocalKeyConsts.MODULE_ID_OPERATOR);
        saveHandlerValue(sceneInstId, LocalKeyConsts.HANDLER_INFO_CARDTYPE, certType, certType, LocalKeyConsts.MODULE_ID_OPERATOR);
        saveHandlerValue(sceneInstId, LocalKeyConsts.HANDLER_INFO_CARDNUM, certNum, certNum, LocalKeyConsts.MODULE_ID_OPERATOR);
        saveHandlerValue(sceneInstId, LocalKeyConsts.HANDLER_INFO_ATTACHMENTS, attachmentValue, attachmentDesc, LocalKeyConsts.MODULE_ID_OPERATOR);
        List<CommonAttrVO> commonAttrList = new ArrayList<>();
        // 获取经办人对象
        List<KiteAttr> handlerAttrs = querySceneInstService.listCommonAttrsByModuleId(sceneInstId,
            LocalKeyConsts.MODULE_ID_OPERATOR);
        // 除经办人名称外 其他属性置灰
        handlerAttrs.stream().forEach(attr -> {
            if (!KiteStringUtils.equals("handler_info_name", attr.getFieldName())) {
                attr.setIsEdit(KeyConsts.IFTRUE_F);
            }
        });
        handlerAttrs.forEach(handlerAttr -> operateSceneInstService.setCommonAttr(sceneInstId, handlerAttr));
        List<InstAttrDTO> instAttrDTOList = CopyToDtoUtil.transInstAttrDtoList(handlerAttrs);
        if (KiteListUtils.isNotEmpty(instAttrDTOList)) {
            commonAttrList = KiteListUtils.isNotEmpty(instAttrDTOList) ?
                instAttrDTOList.stream().map(attrDTO -> KiteBeanUtils.transform(attrDTO, CommonAttrVO.class))
                    .collect(Collectors.toList()) :
                Collections.emptyList();
        }
        return commonAttrList;
    }

    @Override
    public void saveHandlerValue(String sceneInstId, String fieldName, String value, String valueDesc,
                                 String moduleId) {
        //查询四类人的属性
        List<InstAttrDTO> commonAttrList = queryScenePersonService.listKiteConfigAttrsByModuleId(sceneInstId, moduleId)
            .getResultObject();
        List<InstAttrDTO> result = commonAttrList.stream()
            .filter(kiteAttrConfig -> KiteStringUtils.equals(fieldName, kiteAttrConfig.getFieldName()))
            .collect(Collectors.toList());
        if (!KiteListUtils.isEmpty(result)) {
            InstAttrDTO commonAttrVO = result.get(0);

            // 如果是下拉框，下拉值转义
            if (KiteStringUtils.equals(commonAttrVO.getAttrValueTypeId(), KeyValues.DROPDOWN)) {
                valueDesc = Optional.ofNullable(AttrValueCache.getAttrValue(commonAttrVO.getAttrId(), value))
                    .map(attrVal -> attrVal.getAttrValueDesc()).orElse(valueDesc);
            }
            if (KiteStringUtils.isNotBlank(commonAttrVO.getHandlerClass())) {
                ICommonAttrHandler commonAttrHandler = HandlerFactoryUtils.getHandler(commonAttrVO.getHandlerClass());
                if (commonAttrHandler != null) {
                    commonAttrHandler.apply(sceneInstId, fieldName, value, valueDesc);
                }
            }
        }
        SpringUtil.getBean(IOperateSceneCommonService.class).setCommonAttrValue(sceneInstId,
            fieldName, value, valueDesc);
    }

    private KitePosAttrDTO newUserAttr(String fieldName, String value) {
        KitePosAttrDTO attr = new KitePosAttrDTO();
        attr.setCode(fieldName);
        attr.setValue(value);
        return attr;
    }

    @Override
    public PageInfo<Map<String, Object>> queryOppoInfos(Map<String, Object> map) {
        PageInfo<Map<String, Object>> oppoMap = infServiceBus.queryOppoInfo(map);
        return oppoMap;
    }

    @Override
    public PageInfo<PropertyValueVO> queryValueList(Map<String, Object> map) {
        List<PropertyValueVO> valueList = iInfUnifyService.queryValueList(map);
        PageInfo<PropertyValueVO> pageInfo = new PageInfo<PropertyValueVO>();
        pageInfo.setList(valueList);
        pageInfo.setTotal(valueList.size());
        return pageInfo;
    }
    @Override
    public void insertValueList(Map<String, Object> map) {
       iInfUnifyService.insertValueList(map);
    }

    @Override
    public void commitValueList(Map<String, Object> map) {
        String eparchyCode=KiteMapUtils.getString(map,"eparchyCode");
        String name=KiteMapUtils.getString(map,"name");
        String type=KiteMapUtils.getString(map,"type");
        String sceneInstId=KiteMapUtils.getString(map,"sceneInstId");
        String prodInstId=KiteMapUtils.getString(map,"prodInstId");
        KiteSceneInst sceneInst=this.querySceneInstService.getSceneInst(sceneInstId);
        KiteAttr attr22=this.querySceneInstService.getProdInstAttr(sceneInst.getCustId(),prodInstId,"200002822");
        KiteAttr attr23=this.querySceneInstService.getProdInstAttr(sceneInst.getCustId(),prodInstId,"200002823");
        KiteAttr attr21=this.querySceneInstService.getProdInstAttr(sceneInst.getCustId(),prodInstId,"200002821");
        attr22.setValue(name);
        attr23.setValue(eparchyCode);
        attr21.setValue(type);
        operateSceneInstService.setAttr(sceneInstId, InstType.PROD_INST,prodInstId, attr22);
        operateSceneInstService.setAttr(sceneInstId, InstType.PROD_INST,prodInstId, attr23);
        operateSceneInstService.setAttr(sceneInstId, InstType.PROD_INST,prodInstId, attr21);

    }
}
